package com.doyens.controller;

import com.doyens.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(path = "/testString")
    public String testString(Model model){
        System.out.println("hello spring MVC !!!!");
        User user=new User();
        user.setUsername("张三");
        user.setPassword("145");
        user.setAge(18);
        model.addAttribute("user",user );
        return  "success";
    }
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException {
        System.out.println("执行了testVoid方法.....    ");
//        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response );
//        response.sendRedirect(request.getContextPath()+"/index.jsp");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("北京欢迎您");
        return;
    }
    @RequestMapping("/testModeAndView")
    public ModelAndView testModeAndView(){
            ModelAndView mv =new ModelAndView();
        User user=new User();
        user.setUsername("张三");
        user.setPassword("145");
        user.setAge(18);
        mv.addObject("user",user);
        mv.setViewName("success");
        return mv;
     }
     //springmvc定义转发和重定向
    @RequestMapping("/testForwarandRedirect")
    public String testForwarandRedirect(){
        System.out.println("testForwarandRedirect方法执行了....");
        //重定向
//        return "forward:/WEB-INF/pages/success.jsp";
        return "redirect:/index.jsp";
    }
//    @RequestMapping("/testAjax")
//    public void testAjax(@RequestBody String body){
//        System.out.println("testAjax方法执行了...");
//        System.out.println("body = " + body);
//    }
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax方法执行了....");
        System.out.println(user );
        user.setUsername("一一");
        user.setPassword("412");
        user.setAge(20);
        return user;
    }

}
